// 自定义确认弹窗功能
const confirmModal = {
  modal: document.getElementById("confirmModal"),
  message: document.getElementById("confirmMessage"),
  okBtn: document.getElementById("confirmOk"),
  cancelBtn: document.getElementById("confirmCancel"),

  show: function (message, callback) {
    this.message.textContent = message;
    this.modal.style.display = "flex";

    return new Promise(resolve => {
      const handleResult = result => {
        this.hide();
        resolve(result);
        if (callback) callback(result);
      };

      this.okBtn.onclick = () => handleResult(true);
      this.cancelBtn.onclick = () => handleResult(false);
    });
  },

  hide: function () {
    this.modal.style.display = "none";
    this.okBtn.onclick = null;
    this.cancelBtn.onclick = null;
  },
};

// 渲染记录列表
function renderRecords(records) {
  const container = document.getElementById("recordsContainer");
  container.innerHTML = "";

  if (records.length === 0) {
    const emptyItem = document.createElement("li");
    emptyItem.textContent = "暂无保存记录";
    emptyItem.style.padding = "8px";
    emptyItem.style.color = "#666";
    container.appendChild(emptyItem);
    return;
  }

  records.forEach((record, index) => {
    const item = document.createElement("li");
    item.className = "record-item";

    // 添加复选框
    const checkbox = document.createElement("input");
    checkbox.type = "checkbox";
    checkbox.className = "record-checkbox";
    checkbox.dataset.id = record.id;
    checkbox.addEventListener("change", function () {
      this.closest(".record-item").classList.toggle("selected", this.checked);
    });
    item.appendChild(checkbox);

    // 添加点击整行选中功能
    item.addEventListener("click", e => {
      if (e.target.tagName !== "INPUT" && e.target.tagName !== "BUTTON") {
        checkbox.checked = !checkbox.checked;
        checkbox.dispatchEvent(new Event("change"));
      }
    });

    const infoDiv = document.createElement("div");
    infoDiv.className = "record-info";

    const dateSpan = document.createElement("span");
    dateSpan.className = "record-date";
    dateSpan.textContent = record.timestamp;

    const countSpan = document.createElement("span");
    countSpan.className = "record-count";
    countSpan.textContent = `${record.tabCount}个标签页`;

    infoDiv.appendChild(dateSpan);
    infoDiv.appendChild(document.createElement("br"));
    infoDiv.appendChild(countSpan);

    const actionsDiv = document.createElement("div");
    actionsDiv.className = "record-actions";
    const restoreBtn = document.createElement("button");
    restoreBtn.className = "record-action restore-action";
    restoreBtn.textContent = "恢复";
    restoreBtn.addEventListener("click", e => {
      e.stopPropagation();
      const urls = record.tabs.map(tab => tab.url);

      const handleResponse = response => {
        if (response?.success) {
          window.close();
        } else {
          console.error("恢复失败:", response?.error);
        }
      };

      chrome.runtime.sendMessage(
        { action: "restore", urls: urls },
        handleResponse
      );
    });

    const deleteBtn = document.createElement("button");
    deleteBtn.className = "record-action delete-action";
    deleteBtn.textContent = "删除";
    deleteBtn.addEventListener("click", e => {
      e.stopPropagation();
      confirmModal
        .show(
          `确定要删除 ${record.timestamp} 保存的${record.tabCount}个标签页记录吗？`
        )
        .then(confirmed => {
          if (confirmed) {
            chrome.runtime.sendMessage(
              {
                action: "delete",
                recordId: record.id,
              },
              response => {
                if (response?.records) {
                  renderRecords(response.records);
                } else if (response?.error) {
                  console.error("删除失败:", response.error);
                }
              }
            );
          }
        });
    });

    actionsDiv.appendChild(restoreBtn);
    actionsDiv.appendChild(deleteBtn);

    item.appendChild(infoDiv);
    item.appendChild(actionsDiv);
    container.appendChild(item);
  });
}

// 获取选中的记录ID
function getSelectedRecordIds() {
  const checkboxes = document.querySelectorAll(".record-checkbox:checked");
  return Array.from(checkboxes).map(checkbox => checkbox.dataset.id);
}

// 全选/取消全选
document.getElementById("selectAll").addEventListener("change", function () {
  const checkboxes = document.querySelectorAll(".record-checkbox");
  checkboxes.forEach(checkbox => {
    checkbox.checked = this.checked;
    checkbox.dispatchEvent(new Event("change"));
  });
});

// 初始化
document.getElementById("saveBtn").addEventListener("click", () => {
  chrome.runtime.sendMessage({ action: "save" }, response => {
    if (response?.records) {
      renderRecords(response.records);
    } else if (response?.error) {
      console.error("保存失败:", response.error);
    }
  });
});

// 删除选中记录
document.getElementById("deleteSelectedBtn").addEventListener("click", () => {
  const selectedIds = getSelectedRecordIds();
  if (selectedIds.length === 0) {
    confirmModal.show("请先选择要删除的记录").then(() => {});
    return;
  }

  confirmModal
    .show(`确定要删除选中的${selectedIds.length}条记录吗？`)
    .then(confirmed => {
      if (confirmed) {
        // 批量删除选中的记录
        chrome.runtime.sendMessage(
          { action: "deleteSelected", recordIds: selectedIds.map(Number) },
          response => {
            if (response?.records) {
              renderRecords(response.records);
            } else if (response?.error) {
              console.error("删除失败:", response.error);
            }
          }
        );

        // let deletedCount = 0;
        // const deleteSequentially = async () => {
        //   for (const id of selectedIds) {
        //     try {
        //       const response = await new Promise(resolve => {
        //         chrome.runtime.sendMessage(
        //           { action: "delete", recordId: Number(id) },
        //           resolve
        //         );
        //       });

        //       if (!response?.error) {
        //         deletedCount++;
        //         // 立即从DOM中移除已删除的项
        //         const item = document
        //           .querySelector(`.record-checkbox[data-id="${id}"]`)
        //           ?.closest(".record-item");
        //         if (item) {
        //           item.remove();
        //         }
        //       } else {
        //         console.error(`删除记录 ${id} 失败:`, response?.error);
        //       }
        //     } catch (error) {
        //       console.error(`删除记录 ${id} 时出错:`, error);
        //     }
        //   }

        //   // 更新UI状态
        //   document.getElementById("selectAll").checked = false;

        //   // 检查是否已删除所有记录
        //   const container = document.getElementById("recordsContainer");
        //   if (container.children.length === 0) {
        //     const emptyItem = document.createElement("li");
        //     emptyItem.textContent = "暂无保存记录";
        //     emptyItem.style.padding = "8px";
        //     emptyItem.style.color = "#666";
        //     container.appendChild(emptyItem);
        //   }

        //   console.log(`成功删除 ${deletedCount}/${selectedIds.length} 条记录`);
        // };

        // deleteSequentially();
      }
    });
});

// 加载保存的记录
chrome.runtime.sendMessage({ action: "getRecords" }, response => {
  if (response?.records) {
    renderRecords(response.records);
  } else if (response?.error) {
    console.error("加载记录失败:", response.error);
  }
});
